import sys
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QLabel, QPushButton, QFrame, QStackedWidget, QScrollArea
)
from PyQt6.QtCore import Qt

# 导入保护模块
from protection import protection_check
from license_manager import check_license, get_license_info

# 导入各个功能模块
from communication import CommunicationWidget
from greeting import GreetingWidget
from chat import ChatWidget
from resume import ResumeWidget
from log import LogWidget
from work_py import PlaywrightWorker

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        
        # 执行保护检查
        protection_check()
        
        self.setWindowTitle("🤖 智能沟通机器人")
        
        # 强制设置窗口大小
        self.setFixedSize(1200, 740)  # 使用setFixedSize确保大小生效
        # 或者使用以下方法

        # 居中显示窗口
        self.center_window()
        
        # 使用更清爽的配色方案
        self.setStyleSheet("""
            QMainWindow {
                background-color: #f8f9fa;
            }
        """)
        
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(10)
        
        # 创建顶部控制按钮区域
        self.create_control_bar()
        main_layout.addWidget(self.control_bar)
        
        # 创建内容区域
        content_widget = QWidget()
        content_layout = QHBoxLayout(content_widget)
        content_layout.setContentsMargins(0, 0, 0, 0)
        content_layout.setSpacing(10)
        
        # 创建左侧导航栏
        self.create_sidebar()
        content_layout.addWidget(self.sidebar)
        
        # 创建右侧内容区域
        self.create_content_area()
        content_layout.addWidget(self.content_area)
        
        main_layout.addWidget(content_widget)
        
        # 设置默认显示沟通页面
        self.show_communication()
        
        # 控制状态
        self.is_running = False
        self.is_paused = False
        
        # 初始化PlaywrightWorker
        self.worker = PlaywrightWorker()
        self.worker.status_signal.connect(self.on_worker_status_changed)
        

    
    def center_window(self):
        """将窗口居中显示"""
        from PyQt6.QtGui import QScreen
        screen = QApplication.primaryScreen().geometry()
        x = (screen.width() - 1200) // 2
        y = (screen.height() - 800) // 2
        self.move(x, y)
    
    def create_control_bar(self):
        """创建顶部控制按钮栏"""
        self.control_bar = QFrame()
        self.control_bar.setFixedHeight(70)
        
        # 只给容器设置边框和背景
        self.control_bar.setStyleSheet("""
            QFrame {
                background-color: white;
                border-radius: 10px;
                border: 1px solid #e9ecef;
            }
        """)
        
        control_layout = QHBoxLayout(self.control_bar)
        control_layout.setContentsMargins(20, 15, 20, 15)
        
        # 标题 - 单独设置样式，明确无边框
        title_label = QLabel("🤖 沟通机器人控制台")
        title_label.setStyleSheet("""
            QLabel {
                color: #495057;
                font-size: 18px;
                font-weight: bold;
                border: none;
                background-color: transparent;
            }
        """)
        control_layout.addWidget(title_label)
        
        control_layout.addStretch()
        
        # 控制按钮
        self.start_btn = QPushButton("▶️ 开始")
        self.pause_btn = QPushButton("⏸️ 暂停")
        self.stop_btn = QPushButton("⏹️ 停止")
        
        # 按钮样式 - 明确指定无边框
        button_style = """
            QPushButton {
                background-color: #007bff;
                color: white;
                border: none;  /* 明确无边框 */
                padding: 8px 20px;
                border-radius: 6px;
                font-size: 14px;
                font-weight: 500;
                min-width: 80px;
            }
            QPushButton:hover {
                background-color: #0056b3;
            }
            QPushButton:pressed {
                background-color: #004085;
            }
            QPushButton:disabled {
                background-color: #6c757d;
                color: #adb5bd;
            }
        """
        
        pause_style = """
            QPushButton {
                background-color: #ffc107;
                color: #212529;
                border: none;  /* 明确无边框 */
                padding: 8px 20px;
                border-radius: 6px;
                font-size: 14px;
                font-weight: 500;
                min-width: 80px;
            }
            QPushButton:hover {
                background-color: #e0a800;
            }
            QPushButton:pressed {
                background-color: #d39e00;
            }
            QPushButton:disabled {
                background-color: #6c757d;
                color: #adb5bd;
            }
        """
        
        stop_style = """
            QPushButton {
                background-color: #dc3545;
                color: white;
                border: none;  /* 明确无边框 */
                padding: 8px 20px;
                border-radius: 6px;
                font-size: 14px;
                font-weight: 500;
                min-width: 80px;
            }
            QPushButton:hover {
                background-color: #c82333;
            }
            QPushButton:pressed {
                background-color: #bd2130;
            }
            QPushButton:disabled {
                background-color: #6c757d;
                color: #adb5bd;
            }
        """
        
        # 分别设置按钮样式
        self.start_btn.setStyleSheet(button_style)
        self.pause_btn.setStyleSheet(pause_style)
        self.stop_btn.setStyleSheet(stop_style)
        
        # 连接按钮事件
        self.start_btn.clicked.connect(self.start_operation)
        self.pause_btn.clicked.connect(self.pause_operation)
        self.stop_btn.clicked.connect(self.stop_operation)
        
        # 初始状态
        self.pause_btn.setEnabled(False)
        self.stop_btn.setEnabled(False)
        
        control_layout.addWidget(self.start_btn)
        control_layout.addWidget(self.pause_btn)
        control_layout.addWidget(self.stop_btn)
    
    def create_sidebar(self):
        """创建清爽的左侧导航栏"""
        self.sidebar = QFrame()
        self.sidebar.setFixedWidth(200)
        self.sidebar.setStyleSheet("""
            /* 只给主容器设置边框 */
            QFrame#sidebar {
                background-color: white;
                border-radius: 10px;
                border: 1px solid #e9ecef;
            }
            /* 按钮样式，明确指定无边框 */
            QPushButton {
                background-color: transparent;
                color: #495057;
                text-align: left;
                padding: 15px 20px;
                border: none;  /* 明确指定无边框 */
                font-size: 14px;
                font-weight: 500;
                border-radius: 8px;
                margin: 2px 8px;
            }
            QPushButton:hover {
                background-color: #e9ecef;
                color: #007bff;
                border: none;  /* 悬停时也无边框 */
            }
            QPushButton:checked {
                background-color: #007bff;
                color: white;
                border: none;  /* 选中时也无边框 */
            }
            /* 标签样式，明确指定无边框 */
            QLabel {
                border: none;
                background-color: transparent;
            }
        """)
        
        # 给sidebar设置对象名称，这样CSS选择器才能生效
        self.sidebar.setObjectName("sidebar")
        sidebar_layout = QVBoxLayout(self.sidebar)
        sidebar_layout.setContentsMargins(0, 20, 0, 20)
        sidebar_layout.setSpacing(5)
        
  
        # 导航按钮
        nav_buttons = [
            ("💬 沟通配置", self.show_communication),
            ("👋 智能打招呼", self.show_greeting),
            ("🔄 复聊管理", self.show_chat),
            ("📁 简历库", self.show_resume),
            ("📋 系统日志", self.show_log)
        ]
        
        self.nav_buttons = []
        for text, callback in nav_buttons:
            btn = QPushButton(text)
            btn.clicked.connect(callback)
            btn.setCheckable(True)
            self.nav_buttons.append(btn)
            sidebar_layout.addWidget(btn)
        
        # 添加弹性空间
        sidebar_layout.addStretch()
        
        # 状态信息
        status_frame = QFrame()
        status_frame.setStyleSheet("""
            QFrame {
                background-color: #f8f9fa;
                border-radius: 8px;
                margin: 8px;
                padding: 15px;
            }
        """)
        status_layout = QVBoxLayout(status_frame)
        status_layout.setContentsMargins(0, 0, 0, 0)
        
        user_label = QLabel("👤 管理员")
        user_label.setStyleSheet("""
            color: #495057; 
            font-size: 13px;
            font-weight: 500;
            margin-bottom: 5px;
        """)
        
        self.status_label = QLabel("🔴 已停止")
        self.status_label.setStyleSheet("""
            color: #6c757d; 
            font-size: 12px;
        """)
        
        # 添加license有效期显示
        self.license_label = QLabel("📅 获取中...")
        self.license_label.setStyleSheet("""
            color: #28a745; 
            font-size: 11px;
            margin-top: 5px;
        """)
        
        # 获取并显示license信息
        self.update_license_display()
        
        status_layout.addWidget(user_label)
        status_layout.addWidget(self.status_label)
        status_layout.addWidget(self.license_label)
        sidebar_layout.addWidget(status_frame)
    
    def create_content_area(self):
        """创建内容区域"""
        self.content_area = QFrame()
        self.content_area.setStyleSheet("""
            QFrame {
                background-color: white;
                border-radius: 10px;
                border: 1px solid #e9ecef;
            }
        """)
        
        content_layout = QVBoxLayout(self.content_area)
        content_layout.setContentsMargins(0, 0, 0, 0)
        
        # 创建堆叠部件来切换不同页面
        self.stacked_widget = QStackedWidget()
        self.stacked_widget.setStyleSheet("""
            QStackedWidget {
                background-color: transparent;
                border-radius: 10px;
            }
        """)
        
        # 添加各个功能页面
        try:
            self.communication_widget = CommunicationWidget()
            self.greeting_widget = GreetingWidget()
            self.chat_widget = ChatWidget()
            self.resume_widget = ResumeWidget()
            self.log_widget = LogWidget()
            
            self.stacked_widget.addWidget(self.communication_widget)
            self.stacked_widget.addWidget(self.greeting_widget)
            self.stacked_widget.addWidget(self.chat_widget)
            self.stacked_widget.addWidget(self.resume_widget)
            self.stacked_widget.addWidget(self.log_widget)
        except Exception as e:
            error_label = QLabel(f"加载模块时出错: {str(e)}")
            error_label.setStyleSheet("""
                QLabel {
                    color: #dc3545;
                    font-size: 16px;
                    padding: 50px;
                    text-align: center;
                }
            """)
            error_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
            self.stacked_widget.addWidget(error_label)
        
        content_layout.addWidget(self.stacked_widget)
    
    # 控制按钮事件处理
    def start_operation(self):
        """开始操作"""
        self.is_running = True
        self.is_paused = False
        
        self.start_btn.setEnabled(False)
        self.pause_btn.setEnabled(True)
        self.pause_btn.setText("⏸️ 暂停")
        self.stop_btn.setEnabled(True)
        
        self.status_label.setText("🟢 运行中")
        self.status_label.setStyleSheet("color: #28a745; font-size: 12px;")
        
        # 启动PlaywrightWorker
        if not self.worker.isRunning():
            self.worker.running = True
            self.worker.paused = False  # 确保不是暂停状态
            self.worker.status = "start"
            self.worker.start()
        else:
            if self.worker.status != "start":
                self.worker.resume()
        
        print("系统已启动")
    
    def pause_operation(self):
        """暂停/继续操作"""
        if self.is_paused:
            # 继续
            self.is_paused = False
            self.pause_btn.setText("⏸️ 暂停")
            self.status_label.setText("🟢 运行中")
            self.status_label.setStyleSheet("color: #28a745; font-size: 12px;")
            self.worker.status = "start"
            self.worker.resume()
            print("系统已继续")
        else:
            # 暂停
            self.is_paused = True
            self.pause_btn.setText("▶️ 继续")
            self.status_label.setText("🟡 已暂停")
            self.status_label.setStyleSheet("color: #ffc107; font-size: 12px;")
            self.worker.pause()
            print("系统已暂停")
    
    def stop_operation(self):
        """停止操作"""
        self.is_running = False
        self.is_paused = False
        
        self.start_btn.setEnabled(True)
        self.pause_btn.setEnabled(False)
        self.pause_btn.setText("⏸️ 暂停")
        self.stop_btn.setEnabled(False)
        
        self.status_label.setText("🔴 已停止")
        self.status_label.setStyleSheet("color: #6c757d; font-size: 12px;")
        
        # 停止PlaywrightWorker
        self.worker.stop()
        if self.worker.isRunning():
            self.worker.wait()  # 等待线程结束
        
        print("系统已停止")
    
    def on_worker_status_changed(self, status):
        """处理worker状态变化"""
        print(f"Worker状态: {status}")
        message = ""
        # 可以根据需要更新UI状态
        self.status_label.setText(message)
        if status == "running":
            self.status_label.setStyleSheet("color: #28a745; font-size: 12px;")
        elif status == "paused":
            self.status_label.setStyleSheet("color: #ffc107; font-size: 12px;")
        elif status == "stopped":
            self.status_label.setStyleSheet("color: #6c757d; font-size: 12px;")
    
    def on_automation_log(self, message):
        """处理自动化日志消息"""
        print(f"[自动化] {message}")
        # 可以将日志显示到日志界面
    
    def on_operation_completed(self, operation_type, result):
        """处理操作完成事件"""
        status = result.get('status', 'unknown')
        print(f"操作完成: {operation_type} - {status}")

    # 页面切换方法
    def show_communication(self):
        """显示沟通页面"""
        self.stacked_widget.setCurrentIndex(0)
        self.update_nav_buttons(0)
    
    def show_greeting(self):
        """显示打招呼页面"""
        self.stacked_widget.setCurrentIndex(1)
        self.update_nav_buttons(1)
    
    def show_chat(self):
        """显示复聊页面"""
        self.stacked_widget.setCurrentIndex(2)
        self.update_nav_buttons(2)
    
    def show_resume(self):
        """显示简历库页面"""
        self.stacked_widget.setCurrentIndex(3)
        self.update_nav_buttons(3)

    def update_license_display(self):
        """更新license显示信息"""
        try:
            expire_time, status_text = get_license_info()

            if expire_time:
                if "已过期" in status_text:
                    self.license_label.setText(f"📅 {expire_time.strftime('%Y-%m-%d')} (已过期)")
                    self.license_label.setStyleSheet("""
                          color: #dc3545; 
                          font-size: 11px;
                          margin-top: 5px;
                      """)
                else:
                    self.license_label.setText(f"📅 至 {expire_time.strftime('%Y-%m-%d')} ({status_text})")
                    self.license_label.setStyleSheet("""
                          color: #28a745; 
                          font-size: 11px;
                          margin-top: 5px;
                      """)
            else:
                self.license_label.setText(f"📅 {status_text}")
                self.license_label.setStyleSheet("""
                      color: #ffc107; 
                      font-size: 11px;
                      margin-top: 5px;
                  """)
        except Exception as e:
            self.license_label.setText("📅 状态未知")
            self.license_label.setStyleSheet("""
                  color: #6c757d; 
                  font-size: 11px;
                  margin-top: 5px;
              """)
    def show_log(self):
        """显示日志页面"""
        self.stacked_widget.setCurrentIndex(4)
        self.update_nav_buttons(4)
    
    def update_nav_buttons(self, active_index):
        """更新导航按钮状态"""
        for i, btn in enumerate(self.nav_buttons):
            btn.setChecked(i == active_index)

def main():
    # 执行保护检查
    protection_check()
    
    # 检查license
    if not check_license():
        sys.exit(1)
    
    app = QApplication(sys.argv)
    
    # 设置应用程序图标和信息
    app.setApplicationName("智能沟通机器人")
    app.setApplicationVersion("1.0.0")
    app.setOrganizationName("您的公司名称")
    
    window = MainWindow()
    window.show()
    
    sys.exit(app.exec())

if __name__ == "__main__":
    main()


